#include "dialog_config.h"
#include "ui_dialog_config.h"

Dialog_Config::Dialog_Config(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog_Config)
{
    ui->setupUi(this);
    setModal(true);
    setWindowTitle("下线配置计算工具");
    init();
}

Dialog_Config::~Dialog_Config()
{
    delete ui;
}

void Dialog_Config::init()
{

    QStringList headers;
    headers<<"Name"<<"Bit"<<"Value";
    ui->tableWidget->setHorizontalHeaderLabels(headers);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
    ui->tableWidget->horizontalHeader()->setStretchLastSection(true);
    ui->tableWidget->setColumnCount(3);

    _smallTool = new SmallTool();
    QString data = _smallTool->readFile("./config.txt");

    QStringList lines = data.split("\n");

    int len = lines.length();

    int realLen = 0;
    for(int i=0; i<len; i++){
        QString line = lines.at(i);

        if(line.trimmed().isEmpty()) continue;

        realLen++;
        ui->tableWidget->setRowCount(realLen);

        QStringList ls = line.split(":");

        if(ls.length() == 2){
            QString name = QString(ls.at(0)).trimmed();
            QString bit = QString(ls.at(1)).trimmed();

            QTableWidgetItem* item1 = new QTableWidgetItem(name);
            item1->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
            ui->tableWidget->setItem(i, 0, item1);

            QTableWidgetItem* item2 = new QTableWidgetItem(bit);
            item2->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
            ui->tableWidget->setItem(i, 1, item2);

            ui->tableWidget->setItem(i, 2, new QTableWidgetItem("0"));

            if(bit.contains("~")){
                QStringList bits = bit.split("~");
                int size = QString(bits.at(1)).toInt() - QString(bits.at(0)).toInt() + 1;
                item2->setData(Qt::UserRole, size);
            }
            else{
                item2->setData(Qt::UserRole, 1);
            }

        }
        else{
            qWarning()<<"解析数据错误 "<<line;
        }
    }

    //name bit
}

void Dialog_Config::on_pushButton_clicked()
{
    //calc
    ui->lineEdit->setText("");
    QString result;

    int len = ui->tableWidget->rowCount();

    int currentByte = 0;
    int moveBits = 0;

    for(int i=0; i<len; i++){

        QTableWidgetItem* item2 = ui->tableWidget->item(i, 1);

        if(!item2) continue;

        int bit = item2->data(Qt::UserRole).toInt();

        int value = ui->tableWidget->item(i, 2)->text().toInt();

        currentByte = currentByte | (value << moveBits);
        moveBits += bit;

        if(moveBits >= 8){
            //超出8位存储,下一个数

            result.append("0x").append(QByteArray::number(currentByte, 16).toUpper()).append(" ");
            //clear
            moveBits = 0;
            currentByte = 0;
        }
//        qInfo()<<bit<<value;
    }

//    qInfo()<<"data "<<result<<QString(result);
    ui->lineEdit->setText(result);
}
